<template>
  <div>
    <el-image
      v-for="(item,index) in fileList"
      :key="index"
      style="width: 50px; height: 50px;margin-right: 10px;"
      :src="item.url"
      :preview-src-list="[item.url]"
      v-if="checkFileSuffix(item.fileSuffix)"
    />
    <!-- 文件列表 -->
    <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
      <li :key="file.url" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList" v-if="!checkFileSuffix(file.fileSuffix)">
        <el-link :href="`${file.url}`" :underline="false" target="_blank">
          <span class="el-icon-document" style="color: #00afff"> {{ getFileName(file.notesName || file.originalName) }} </span>
        </el-link>
<!--        <div class="ele-upload-list__item-content-action">-->
<!--          <el-link :underline="false" @click="handleDelete(index)" type="danger">删除</el-link>-->
<!--        </div>-->
      </li>
    </transition-group>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { listByIds } from '@/api/system/oss'

export default {
  name: 'ImageOrFile',
  props: {
    value: [String, Object, Array]
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: []
    }
  },
  watch: {
    value: {
      async handler(val) {
        if (val) {
          // 首先将值转为数组
          let list;
          if (Array.isArray(val)) {
            list = val;
          } else {
            await listByIds(val).then(res => {
              list = res.data;
            })
          }
          // 然后将数组转为对象数组
          this.fileList = [ ...list ]
          /*this.fileList = list.map(item => {
            // 此处name使用ossId 防止删除出现重名
            item = { name: item.ossId, url: item.url, ossId: item.ossId };
            return item;
          });*/
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    checkFileSuffix(fileSuffix) {
      let arr = ["png", "jpg", "jpeg"];
      return arr.some(type => {
        return fileSuffix.indexOf(type) > -1;
      });
    },
    // 获取文件名称
    getFileName(name) {
      // 如果是url那么取最后的名字 如果不是直接返回
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
  }
}
</script>

<style scoped>

</style>
